package com.yc.star.booksystem.controller;

import com.yc.star.booksystem.model.*;
import com.yc.star.booksystem.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;


    @RequestMapping(value = "/addBook")
    public Result<String> addBook(BookInfo bookInfo) {
        log.info("添加图书:{}", bookInfo);
        if (!StringUtils.hasLength(bookInfo.getBookName())
                || !StringUtils.hasLength(bookInfo.getAuthor())
                || bookInfo.getCount()<0
                || bookInfo.getPrice().compareTo(BigDecimal.ZERO) < 0
                || !StringUtils.hasLength(bookInfo.getPublish())
                || bookInfo.getStatus() == null
        ) {
            return Result.fail("参数错误！");
        }
        try {
            bookService.addBook(bookInfo);
            return Result.success("");
        } catch (Exception e) {
            log.error("添加图书失败", e);
            return Result.fail("内部错误，请联系管理员");
        }
    }

    @RequestMapping("/getListByPage")
    public Result<PageResult<BookInfo>> getListByPage(PageRequest pageRequest) {
        log.info("查询列表信息："+pageRequest);
        if (pageRequest.getCurrentPage()<1) {
            return Result.fail("非法参数！");
        }
        return Result.success(bookService.getListByPage(pageRequest));
    }

    @RequestMapping("/queryBookById")
    public BookInfo queryBookById(Integer bookId) {
        log.info("bookId:"+bookId);
        return bookService.queryBookById(bookId);
    }

    @RequestMapping("/updateBook")
    public boolean updateBook(BookInfo bookInfo) {
        log.info("图书信息："+bookInfo);
        if (bookInfo.getId() < 0) {
            return false;
        }
        try {
            bookService.updateBook(bookInfo);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    @RequestMapping("/batchDelete")
    public boolean batchDelete(@RequestParam List<Integer> ids) {
        log.info("id列表："+ids);

        try {
            bookService.batchDelete(ids);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }
}
